/* eslint-disable react-refresh/only-export-components */
import { PropsWithChildren, FC, memo, useState, useReducer, useEffect } from "react";
import {
  LeftCircleOutlined,
  EllipsisOutlined,
  PlusOutlined,
  SoundOutlined,
  SoundFilled,
  SkinOutlined
} from "@ant-design/icons";
import { changeGroupCommendName, delectGroupUser, SendMessage } from "@/api/xhr/message";
import { useNavigate } from "react-router-dom";
import AddGroupComponent from "../../commponents/AddGroupComponent";
import AddUserToGroupComponent from "../../commponents/AddUserToGroupComponent";
import {
  Drawer,
  Avatar,
  Tooltip,
  Button,
  Input,
  message,
  Modal,
  Switch
} from "antd";
import TopSearch from "@/components/TopSearch";
import { useSelector } from "react-redux";
import SoundManager from "@/util/sound";

type TypeProps = {
  type: "group" | "friend";
  detail: any;
};

const DrawerCom: FC<
  PropsWithChildren<{
    detail: any;
    showDrawer: any;
    setshowDrawer: (params: boolean) => void;
  }>
> = ({ detail, showDrawer, setshowDrawer }) => {
  const { confirm } = Modal;
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const navgator = useNavigate();
  const [formdata, dispatch] = useReducer(formreducer, {
    groupCommendName: detail.usergroupName,
    commendName: detail.userCommendName,
    groupName: detail.groupInfo.name
  });
  const [groupuserdetail, setgroupuserdetail] = useState(detail.userList);
  const [searchVal, setsearchVal] = useState("");
  // 消息提示音开关状态
  const [soundEnabled, setSoundEnabled] = useState(
    SoundManager.getInstance().isSoundEnabled()
  );
  
  // 添加新状态控制添加用户到群聊的弹框
  const [showAddUserToGroup, setShowAddUserToGroup] = useState(false);

  // 更新消息提示音状态
  const handleSoundToggle = (checked: boolean) => {
    SoundManager.getInstance().toggleSound(checked);
    setSoundEnabled(checked);
  };

  // 测试提示音
  const testSound = () => {
    console.log("测试声音");
    SoundManager.getInstance().playMessageSound(
      false,
      "测试",
      "这是一条测试消息"
    );
  };

  // 修改添加用户到群聊的方法
  function handelAddGroup() {
    // 如果当前用户是群主，则允许添加用户
    if (detail.groupInfo && userinfo.id === detail.groupInfo.creatorId) {
      setShowAddUserToGroup(true);
    } else {
      message.info("只有群主可以添加成员");
    }
  }
  function formreducer(state: any, action: { type: string; value: string }) {
    switch (action.type) {
      case "groupCommendName":
        return {
          ...state,
          groupCommendName: action.value
        };
      case "commendName":
        return {
          ...state,
          commendName: action.value
        };
      case "groupName":
        return {
          ...state,
          groupName: action.value
        };
      default:
        throw new Error("reducer 类型报错了");
    }
  }
  function searchFunc(datavalue: string) {
    if (datavalue) {
      setgroupuserdetail(
        detail.userList.filter(data => {
          return data.name.indexOf(datavalue) !== -1;
        })
      );
    } else {
      setgroupuserdetail(detail.userList);
    }
  }
  async function changeFormData({ type }: { type: string }) {
    let updated = false;
    let groupNameRes;
    let commendNameRes;
    
    switch (type) {
      case "groupCommendName":
        if (formdata.groupCommendName === detail.usergroupName) return;
        groupNameRes = await changeGroupCommendName({
          type: "groupName",
          groupName: formdata.groupCommendName,
          userId: userinfo.id,
          groupId: detail.groupInfo.id
        });
        
        if (groupNameRes.statusCode === 200) {
          updated = true;
          // 更新本地detail，这样UI会立即反映变化
          detail.usergroupName = formdata.groupCommendName;
          
          // 发送自定义事件更新左侧消息列表
          const updateEvent = new CustomEvent("updateGroupInfo", {
            detail: {
              type: "groupName",
              groupId: detail.groupInfo.id,
              newName: formdata.groupCommendName
            }
          });
          window.dispatchEvent(updateEvent);
          
          message.success("群聊备注名称已更新");
        }
        break;
        
      case "commendName":
        if (formdata.commendName === detail.userCommendName) return;
        commendNameRes = await changeGroupCommendName({
          type: "userCommendName",
          userCommendName: formdata.commendName,
          userId: userinfo.id,
          groupId: detail.groupInfo.id
        });
        
        if (commendNameRes.statusCode === 200) {
          updated = true;
          // 更新本地detail
          detail.userCommendName = formdata.commendName;
          message.success("群聊昵称已更新");
        }
        break;
        
      case "groupName":
        if (formdata.groupName == detail.groupInfo.name) return;
        break;
        
      default:
        throw new Error("reducer 类型报错了");
    }
    
    // 如果有更新，触发刷新事件
    if (updated) {
      // 触发MessageHeader组件重新渲染
      const refreshEvent = new CustomEvent("refreshHeader");
      window.dispatchEvent(refreshEvent);
    }
  }
  async function handeldelect() {
    if (detail.groupInfo.creatorId === userinfo.id) {
      confirm({
        title: "提示",
        content: "群主退出群聊会解散群聊",
        onOk() {
          delect();
        }
      });
    } else {
      confirm({
        title: "提示",
        content: "确定退出群聊吗？",
        onOk() {
          delect();
        }
      });
    }
  }
  async function delect() {
    try {
      // 先发送退出群聊的系统消息
      const exitMessage = `${userinfo.userName || "用户"} 退出了群聊`;
      await SendMessage({
        id: detail.groupInfo.id,
        userId: userinfo.id,
        content: exitMessage,
        type: "group",
        messageType: "system", // 指定消息类型为system
        messageSendType: 0 // 设置为系统消息
      });
      
      // 再执行退出群聊操作
      const res = await delectGroupUser({
        userId: userinfo.id,
        groupId: detail.groupInfo.id
      });
      
      if (res.statusCode == 200) {
        // 触发更新聊天列表的事件
        const updateEvent = new CustomEvent("updateMessageList", {
          detail: {
            action: "removeGroup",
            groupId: detail.groupInfo.id
          }
        });
        window.dispatchEvent(updateEvent);
        
        message.success("退出成功");
        navgator("/home/message");
      }
    } catch (error) {
      console.error("退出群聊失败:", error);
      message.error("退出群聊失败");
    }
  }
  return (
    <div className="bg-slate-500 h-[500px] w-[0px] z-50 absolute right-0">
      <Drawer
        title="群聊信息"
        open={showDrawer}
        getContainer={false}
        placement="right"
        width={250}
        onClose={() => {
          setshowDrawer(false);
        }}
      >
        <TopSearch
          value={searchVal}
          setvalue={setsearchVal}
          searchFunc={searchFunc}
        ></TopSearch>

        {/* 消息提示音开关 */}
        <div className="mb-3 flex justify-between items-center border-b-[1px] border-slate-200 pb-2">
          <span className="flex items-center">
            {soundEnabled ? <SoundFilled /> : <SoundOutlined />}
            <span className="ml-2">消息提示音</span>
          </span>
          <div className="flex items-center">
            <Button
              type="link"
              size="small"
              onClick={testSound}
              className="mr-2"
            >
              测试
            </Button>
            <Switch checked={soundEnabled} onChange={handleSoundToggle} />
          </div>
        </div>

        {/* 主题设置开关 */}
        <div className="w-full mb-3 flex justify-between items-center border-b-[1px] border-slate-200 pb-2">
          <span className="flex items-center">
            <SkinOutlined />
            <span className="ml-2">聊天主题</span>
          </span>
          <div className="flex items-center">
            <Button
              type="link"
              size="small"
              onClick={() => {
                setshowDrawer(false);
                setTimeout(() => {
                  // 在抽屉关闭后，发送一个自定义事件来触发主题设置打开
                  const event = new CustomEvent("openThemeSettings");
                  window.dispatchEvent(event);
                }, 300);
              }}
            >
              设置
            </Button>
          </div>
        </div>

        <div className="pb-[4px] flex flex-wrap overflow-y-scroll scrollbar-hide w-full scrollbar select-none cursor-auto overflow-x-hidden max-h-[140px] border-b-[1px] border-slate-200 ">
          {groupuserdetail.length
            ? groupuserdetail.map(item => {
                return (
                  <div
                    className="h-[65px] w-[57px] mt-1 mr-[10px] flex justify-center items-center flex-col"
                    key={item.id}
                  >
                    <div className="relative">
                      <Avatar shape="square" size={48} src={item.avatar} />
                    </div>
                    {item.name?.length > 6 ? (
                      <Tooltip title={item.name} color="#87d068" key="#87d068">
                        <div className="max-w-full truncate whitespace-nowrap overflow-hidden text-center ">
                          {item.name}
                        </div>
                      </Tooltip>
                    ) : (
                      <div className="w-12 truncate whitespace-nowrap overflow-hidden text-center">
                        {item.name}
                      </div>
                    )}
                  </div>
                );
              })
            : ""}
          <div
            className="h-[57px] w-[57px] mt-2 mr-[10px] flex justify-center items-center flex-col border-[1px] border-slate-200 border-dashed rounded"
            onClick={handelAddGroup}
          >
            <div className="relative ">
              <PlusOutlined />
            </div>
          </div>
        </div>
        <div className="py-[8px] text-xs border-b-[1px] border-slate-200 ">
          <div className="flex flex-col">
            <div className="text-left">群聊名称（群主可修改）:</div>
            <Input
              size={"small"}
              variant="borderless"
              value={formdata.groupName}
              className="p-0 text-gray-200"
              disabled={detail.groupInfo}
              onChange={e =>
                dispatch({ type: "groupName", value: e.target.value })
              }
              onFocus={e => {
                e.target.style.color = "black";
              }}
              onBlur={e => {
                changeFormData({ type: "groupName" });
                e.target.style.color = "rgb(229 231 235)";
              }}
            />
          </div>
          <div className="flex flex-col">
            <div className="text-left">群聊备注名称:</div>
            <Input
              size={"small"}
              variant="borderless"
              placeholder={detail.userCommendName ? "" : "修改群聊备注名称"}
              value={formdata.groupCommendName}
              className="p-0 text-gray-200"
              onChange={e =>
                dispatch({ type: "groupCommendName", value: e.target.value })
              }
              onFocus={e => {
                e.target.style.color = "black";
              }}
              onBlur={e => {
                changeFormData({ type: "groupCommendName" });
                e.target.style.color = "rgb(229 231 235)";
              }}
            />
          </div>
          <div className="flex flex-col">
            <div className="text-left">群聊备注名:</div>
            <Input
              size={"small"}
              variant="borderless"
              placeholder={formdata.commendName ? "" : "修改在该群的昵称"}
              value={formdata.commendName}
              className="p-0"
              onChange={e =>
                dispatch({ type: "commendName", value: e.target.value })
              }
              onFocus={e => {
                e.target.style.color = "black";
              }}
              onBlur={e => {
                changeFormData({ type: "commendName" });
                e.target.style.color = "rgb(229 231 235)";
              }}
            />
          </div>
        </div>
        <div className=" border-b-[1px] border-slate-200 py-2">
          <Button danger type="text" onClick={handeldelect}>
            退出群聊
          </Button>
        </div>
      </Drawer>
      
      {/* 添加用户到群聊的弹框 */}
      {showAddUserToGroup && (
        <AddUserToGroupComponent
          show={showAddUserToGroup}
          setshow={setShowAddUserToGroup}
          groupId={detail.groupInfo.id}
          currentGroupUsers={detail.userList}
        />
      )}
    </div>
  );
};

const MessageHeader: FC<PropsWithChildren<TypeProps>> = ({ detail, type }) => {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const [showDrawer, setshowDrawer] = useState<boolean>(false);
  const navgator = useNavigate();
  // 添加state记录群聊名称，用于更新UI
  const [groupDisplayName, setGroupDisplayName] = useState<string>(
    type === "group" 
      ? (detail.usergroupName ? detail.usergroupName : detail.groupInfo.name)
      : detail.name
  );

  // 消息提示音设置 - 好友聊天
  const [soundEnabled, setSoundEnabled] = useState(
    SoundManager.getInstance().isSoundEnabled()
  );
  const [showFriendDrawer, setShowFriendDrawer] = useState(false);

  // 添加监听事件，当群名称更新时刷新头部显示
  useEffect(() => {
    const handleRefreshHeader = () => {
      if (type === "group") {
        setGroupDisplayName(
          detail.usergroupName ? detail.usergroupName : detail.groupInfo.name
        );
      }
    };
    
    window.addEventListener("refreshHeader", handleRefreshHeader);
    
    return () => {
      window.removeEventListener("refreshHeader", handleRefreshHeader);
    };
  }, [detail, type]);

  // 更新消息提示音状态
  const handleSoundToggle = (checked: boolean) => {
    SoundManager.getInstance().toggleSound(checked);
    setSoundEnabled(checked);
  };

  // 测试提示音
  const testSound = () => {
    console.log("测试声音");
    SoundManager.getInstance().playMessageSound(
      false,
      "测试",
      "这是一条测试消息"
    );
  };

  function handelShowDrawer() {
    if (type === "group") {
      setshowDrawer(true);
    } else {
      setShowFriendDrawer(true);
    }
  }
  const [showAddGroup, setShowAddGroup] = useState<boolean>(false);
  return (
    <div className="relative">
      {type == "group" ? (
        <DrawerCom
          showDrawer={showDrawer}
          setshowDrawer={setshowDrawer}
          detail={detail}
        ></DrawerCom>
      ) : (
          <div className="bg-slate-500 h-[500px] w-[0px] z-50 absolute right-0">
          <Drawer
          title="聊天设置"
          open={showFriendDrawer}
          getContainer={false}
          placement="right"
          width={250}
          onClose={() => setShowFriendDrawer(false)}
        >
          {/* 好友聊天设置 */}
          <div className="mb-3 flex justify-between items-center border-b-[1px] border-slate-200 pb-2">
            <span className="flex items-center">
              {soundEnabled ? <SoundFilled /> : <SoundOutlined />}
              <span className="ml-2">消息提示音</span>
            </span>
            <div className="flex items-center">
              <Button
                type="link"
                size="small"
                onClick={testSound}
                className="mr-2"
              >
                测试
              </Button>
              <Switch checked={soundEnabled} onChange={handleSoundToggle} />
            </div>
          </div>

          {/* 头像展示 */}
          <div className="py-4 flex justify-center border-b-[1px] border-slate-200">
            <Avatar size={64} src={detail.avatar} />
          </div>

          {/* 基本信息 */}
          <div className="py-2 text-xs border-b-[1px] border-slate-200">
            <div className="flex justify-between mb-2">
              <span>好友昵称</span>
              <span>{detail.name}</span>
            </div>
            <div className="flex justify-between">
              <span>用户ID</span>
              <span>{detail.id}</span>
            </div>
          </div>
        </Drawer>
        </div>

      )}
      <div className="h-12 flex justify-between items-center px-3 pt-3 pb-2 border-b-2 border-b-gray-300">
        <LeftCircleOutlined
          onClick={() => {
            navgator(-1);
          }}
        />
        <div className="text-[18px] tracking-wider">
          {type === "group" ? groupDisplayName : detail.name}
        </div>
        <EllipsisOutlined className="text-[18px]" onClick={handelShowDrawer} />
      </div>
      {showAddGroup ? (
        <AddGroupComponent
          show={showAddGroup}
          setshow={setShowAddGroup}
          selectedFriend={detail.userList
            .filter(data => data.id !== userinfo.id)
            .map(item => {
              return {
                ...item,
                checked: true
              };
            })}
        ></AddGroupComponent>
      ) : (
        ""
      )}
    </div>
  );
};

export default memo(MessageHeader);
